<template>
	<view class="page-container">
		<!-- 个人信息列表 -->
		<view class="info-list">
			<!-- 头像 -->
			<view class="info-item">
				<text class="item-label">头像</text>
				<view class="item-right">
					<button class="reset-button avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<wd-img :src="utils.getAvatarPath(userInfo.avatar)" width="80rpx" height="80rpx" round class="avatar-img" />
					</button>
					<wd-icon name="arrow-right" size="16px" color="#c8c9cc" />
				</view>
			</view>

			<view class="info-item" @click="editField('sn', '用户ID', userInfo.sn, 'text')">
				<text class="item-label">用户ID</text>
				<view class="item-right">
					<text class="item-value">{{ userInfo.sn || '未设置' }}</text>
					<wd-icon name="arrow-right" size="16px" color="#c8c9cc" />
				</view>
			</view>

			<view class="info-item" @click="editField('nickname', '昵称', userInfo.nickname, 'text')">
				<text class="item-label">昵称</text>
				<view class="item-right">
					<text class="item-value">{{ userInfo.nickname || '未设置' }}</text>
					<wd-icon name="arrow-right" size="16px" color="#c8c9cc" />
				</view>
			</view>

			<view class="info-item" @click="editField('introduction', '个人简介', userInfo.introduction, 'textarea')">
				<text class="item-label">个人简介</text>
				<view class="item-right">
					<text class="item-value">{{ userInfo.introduction || '这人很懒，没有留下什么...' }}</text>
					<wd-icon name="arrow-right" size="16px" color="#c8c9cc" />
				</view>
			</view>
		</view>

		<!-- 性别选择器 -->
		<wd-picker
			:columns="genderOptions"
			:show="showGender"
			label="性别"
			v-model="userInfo.gender"
			:display-format="getGenderText"
			align-right
			@confirm="onGenderConfirm"
			@cancel="showGender = false"
			@close="showGender = false"
		/>

		<!-- 日期选择器 -->
		<wd-datetime-picker v-model="dateValue" :minDate="8594000" :maxDate="(new Date()).getTime()" type="date" :show="showDate" label="生日" :display-format="formatBirthdayDisplay" align-right @confirm="onDateConfirm" />

		<!-- 编辑弹窗 -->
		<wd-popup v-model="showEditPopup" position="bottom" :close-on-click-modal="false">
			<view class="edit-popup">
				<view class="drag-indicator"></view>
				<view class="popup-header">
					<view class="close-btn" @click="cancelEdit">
						<text>✕</text>
					</view>
				</view>
				<view class="popup-content">
					<view class="input-container">
						<text class="input-label">{{ editTitle }}</text>
						<!-- 昵称 -->
						<wd-input
							v-if="editField_ == 'nickname'"
							type="nickname"
							v-model="editValue"
							:placeholder="editPlaceholder"
							:maxlength="getMaxLength()"
							clearable
							show-word-limit
							:error="inputError"
							@input="validateInput"
						/>
						<wd-input
							v-else-if="editType !== 'textarea'"
							v-model="editValue"
							:placeholder="editPlaceholder"
							:maxlength="getMaxLength()"
							clearable
							show-word-limit
							:error="inputError"
							@input="validateInput"
						/>
						<wd-textarea
							v-else
							v-model="editValue"
							:placeholder="editPlaceholder"
							:maxlength="getMaxLength()"
							show-word-limit
							auto-height
							clearable
							:error="inputError"
						/>
					</view>
				</view>
				<view class="popup-footer">
					<view class="btn-group">
						<view class="cancel-btn" @click="cancelEdit">
							<text>取消</text>
						</view>
						<view class="confirm-btn" :class="{ disabled: !canConfirm }" @click="confirmEdit">
							<text>确定</text>
						</view>
					</view>
				</view>
			</view>
		</wd-popup>
	</view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import { ref, computed } from 'vue';
import { baseAPI } from '@/api/index.js';
import { uploadImage } from '@/utils/upload.js';
import { useUserStore } from '@/store/user';
import utils from '@/utils/utils.js';

//页面公共变量
const userStore = useUserStore();
const userInfo = ref({});
const showGender = ref(false);
const showDate = ref(false);
const showEditPopup = ref(false);
const editField_ = ref('');
const editTitle = ref('');
const editValue = ref('');
const editType = ref('input');
const dateValue = ref('');
const inputError = ref(false);
const errorMessage = ref('');
const editPlaceholder = ref('');

const genderOptions = [
	{ label: '未知', value: 0 },
	{ label: '男', value: 1 },
	{ label: '女', value: 2 }
];

// 计算属性
const canConfirm = computed(() => {
	const value = editValue.value;
	const field = editField_.value;

	// 如果有验证错误，不能确认
	if (inputError.value) {
		return false;
	}

	// 根据不同字段进行验证
	switch (field) {
		case 'nickname':
			// 昵称必须有值且不为空
			return value && value.trim().length > 0;
		case 'sn':
			// 用户ID可以为空，但如果有值则必须通过验证
			return true; // 如果没有验证错误，就可以确认
		default:
			// 其他字段必须有值
			return value && value.trim().length > 0;
	}
});

// 获取最大长度限制
function getMaxLength() {
	switch (editField_.value) {
		case 'sn':
			return 15;
		case 'nickname':
			return 24;
		case 'introduction':
			return 100;
		default:
			return 50;
	}
}

// 页面生命周期
onLoad(() => {
	getUserInfo();
});

onShow(() => {});

// 页面函数
function getUserInfo() {
	baseAPI.get('user/getInfo').then((res) => {
		if (res.code === 200) {
			userInfo.value = res.result;
			// 设置生日默认值为13位数字时间戳
			if (userInfo.value.birthday) {
				dateValue.value = new Date(userInfo.value.birthday).getTime();
			}
		}
	});
}

function getGenderText(items) {
	return items.label;
}

function formatBirthdayDisplay(value) {
	// 如果有用户生日信息，显示用户生日
	if (userInfo.value.birthday) {
		return userInfo.value.birthday;
	}
	// 如果没有生日信息，显示"未设置"
	return '未设置';
}

function editField(field, title, value, type = 'input') {
	editField_.value = field;
	editTitle.value = title;
	editValue.value = value || '';
	editType.value = type;
	inputError.value = false;
	errorMessage.value = '';

	// 设置占位符文本
	switch (field) {
		case 'sn':
			editPlaceholder.value = '请输入用户ID（6-15个字符）';
			break;
		case 'nickname':
			editPlaceholder.value = '请输入昵称（2-24个字符）';
			break;
		case 'introduction':
			editPlaceholder.value = '请输入个人简介';
			break;
		default:
			editPlaceholder.value = '请输入内容';
			break;
	}

	showEditPopup.value = true;
}

function cancelEdit() {
	showEditPopup.value = false;
	editValue.value = '';
	inputError.value = false;
	errorMessage.value = '';
	editPlaceholder.value = '';
}

function validateInput() {
	inputError.value = false;
	errorMessage.value = '';

	const value = editValue.value;
	const field = editField_.value;

	switch (field) {
		case 'nickname':
			if (!value || value.trim().length === 0) {
				inputError.value = true;
				errorMessage.value = '昵称不能为空';
			} else if (value.length < 2) {
				inputError.value = true;
				errorMessage.value = '昵称长度不能少于2个字符';
			} else if (value.length > 24) {
				inputError.value = true;
				errorMessage.value = '昵称长度不能超过24个字符';
			}
			break;
		case 'sn':
			if (value && value.length > 0) {
				if (value.length < 6) {
					inputError.value = true;
					errorMessage.value = '用户ID长度不能少于6个字符';
				} else if (value.length > 15) {
					inputError.value = true;
					errorMessage.value = '用户ID长度不能超过15个字符';
				}
			}
			break;
	}
}

function confirmEdit() {
	validateInput();

	if (inputError.value) {
		return;
	}

	if (!canConfirm.value) {
		return;
	}

	updateProfile(editField_.value, editValue.value);
}

function onGenderConfirm({ value, selectedItems }) {
	showGender.value = false;
	const selectedValue = selectedItems ? selectedItems.value : value;
	updateProfile('gender', String(selectedValue));
}

function onDateConfirm({ value }) {
	showDate.value = false;

	// 将时间戳转换为日期字符串格式 YYYY-MM-DD
	const date = new Date(value);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const dateStr = `${year}-${month}-${day}`;

	// 提交更新
	updateProfile('birthday', dateStr);
}

async function onChooseAvatar(e) {
	const avatar = await uploadImage({
		url: e.detail.avatarUrl
	});

	updateProfile('avatar', avatar);
}

function updateProfile(field, value) {
	const loadingTitle = field === 'avatar' ? '保存中...' : '更新中...';

	uni.showLoading({
		title: loadingTitle
	});

	baseAPI
		.post('user/updateProfile', {
			field: field,
			value: value
		})
		.then((res) => {
			if (res.code === 200) {
				uni.showToast({
					title: '更新成功',
					icon: 'none'
				});

				// 更新本地用户信息
				userInfo.value[field] = value;
				userStore.setUserInfo(res.result);

				// 关闭编辑弹窗
				if (showEditPopup.value) {
					showEditPopup.value = false;
					editValue.value = '';
					inputError.value = false;
					errorMessage.value = '';
				}
			} else {
				uni.showToast({
					title: res.message || '更新失败',
					icon: 'none'
				});
			}
		});
}
</script>

<style lang="scss" scoped>
.page-container {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx;
}

.info-list {
	background: #fff;
	border-radius: 16rpx;
	overflow: hidden;
}

.info-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 32rpx;
	border-bottom: 1rpx solid #f5f5f5;

	&:last-child {
		border-bottom: none;
	}

	&:active {
		background: #f8f8f8;
	}
}

.item-label {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.item-right {
	display: flex;
	align-items: center;
	gap: 16rpx;
	flex: 1;
	justify-content: flex-end;
}

.item-value {
	font-size: 30rpx;
	color: #666;
	max-width: 400rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	text-align: right;
}

.avatar-wrapper {
	position: relative;
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	overflow: hidden;
}

.avatar-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.upload-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(255, 255, 255, 0.8);
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
}

// 编辑弹窗 - 全新现代化设计
.edit-popup {
	background: #fff;
	border-radius: 32rpx 32rpx 0 0;
	overflow: hidden;
	max-height: 85vh;
	position: relative;
}

.drag-indicator {
	position: absolute;
	top: 16rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 6rpx;
	background: #e0e0e0;
	border-radius: 3rpx;
	z-index: 1;
}

.popup-header {
	display: flex;
	align-items: flex-start;
	justify-content: flex-end;
	padding: 48rpx 32rpx 24rpx;
	border-bottom: 1rpx solid #f8f8f8;
}

.close-btn {
	width: 56rpx;
	height: 56rpx;
	background: #f5f5f5;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s ease;

	&:active {
		background: #e8e8e8;
		transform: scale(0.9);
	}
}

.popup-content {
	padding: 32rpx;
}

.input-container {
	.input-label {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
		display: block;
	}
}

.popup-footer {
	padding: 24rpx 32rpx 40rpx;
	background: #fff;
}

.btn-group {
	display: flex;
	gap: 20rpx;

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 22rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 600;
		transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative;
		overflow: hidden;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: currentColor;
			opacity: 0;
			transition: opacity 0.2s ease;
		}

		&:active::before {
			opacity: 0.1;
		}

		text {
			position: relative;
			z-index: 1;
		}
	}

	.cancel-btn {
		background: #f8f9fa;
		color: #6c757d;
		border: 2rpx solid #e9ecef;

		&:active {
			background: #e9ecef;
			transform: translateY(2rpx);
		}
	}

	.confirm-btn {
		background: $-color-theme;
		box-shadow: 0 8rpx 24rpx rgba(15, 220, 120, 0.3);

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 4rpx 12rpx rgba(15, 220, 120, 0.4);
		}

		&.disabled {
			background: #e5e7eb;
			color: #9ca3af;
			box-shadow: none;

			&:active {
				transform: none;
			}

			&::before {
				display: none;
			}
		}
	}
}
</style>
